<template>
  <op-dialog
    v-if="dialogVisible"
    :title="title"
    v-model="dialogVisible"
    :buttonList="buttonList"
    width="960px"
    :height="height"
    noFullscreen
    @close="handleClose"
    @confirm="buttonClick"
  >
    <op-form ref="formRef" v-bind="formConfig" :formData="formData" />
    <sign-drawing ref="signDrawingRef" v-bind="attrs" />
  </op-dialog>
</template>

<script setup>
import SignDrawing from './SignDrawing.vue';

const attrs = useAttrs();

const props = defineProps({
  title: {
    type: String,
    default: 'Signature Approval',
  },
  height: {
    type: String,
    default: '350px',
  },

  formConfig: {
    type: Object,
    default: () => ({
      formList: [
        {
          prop: 'signatureName',
          label: 'Full name：',
          component: 'input',
          itemConfig: {
            rules: [{ required: true, message: 'Full name is requred!' }],
          },
          bindConfig: {
            placeholder: 'Please enter',
          },
        },
      ],
      formConfig: {
        labelWidth: '120px',
        'label-position': 'left',
      },
    }),
  },
  buttonList: {
    type: Array,
    default: () => [
      {
        type: 'primary',
        prop: 'apply',
        label: 'Apply',
      },
    ],
  },
});

// // ref
const formRef = ref();
const signDrawingRef = ref();

const emits = defineEmits(['getSign', 'clearDraw']);

const dialogVisible = ref(false);
const formData = ref({});

function init(sign, row) {
  dialogVisible.value = true;
  formData.value = row;
  nextTick(() => {
    signDrawingRef.value.init(sign, row);
  });
}

function buttonClick(prop) {
  // 有签名
  signDrawingRef.value.getCanvasInfo(res => {
    if (res) {
      formRef.value.validate(() => {
        emits('getSign', { ...formData.value }, res);
        dialogVisible.value = false;
        handleClose();
      });
    } else {
      ElMessage.warning('Please Signature');
      return;
    }
  });
}

function handleClose() {
  formData.value = {};
  dialogVisible.value = false;
}

defineExpose({
  init,
  dialogVisible,
});
</script>

<style lang="scss" scoped>
.signTitle {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.signWrap {
  width: 920px;
  height: 280px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ccc;
}
</style>
